interface BookmarkData {
    bookId: string;
    chapterId: string;
    index: number;
    timestamp: number;
}

class BookmarkDB {
    private dbName = 'bookReaderDB';
    private version = 1;
    private db: IDBDatabase | null = null;

    async init() {
        if (this.db) return;

        return new Promise<void>((resolve, reject) => {
            const request = indexedDB.open(this.dbName, this.version);

            request.onerror = () => reject(request.error);

            request.onsuccess = () => {
                this.db = request.result;
                resolve();
            };

            request.onupgradeneeded = (event) => {
                const db = (event.target as IDBOpenDBRequest).result;
                if (!db.objectStoreNames.contains('bookmarks')) {
                    const store = db.createObjectStore('bookmarks', { keyPath: 'bookId' });
                    store.createIndex('timestamp', 'timestamp');
                }
            };
        });
    }

    async saveBookmark(data: BookmarkData): Promise<void> {
        await this.init();
        return new Promise((resolve, reject) => {
            const transaction = this.db!.transaction(['bookmarks'], 'readwrite');
            const store = transaction.objectStore('bookmarks');
            const request = store.put(data);

            request.onerror = () => reject(request.error);
            request.onsuccess = () => resolve();
        });
    }

    async getBookmark(bookId: string): Promise<BookmarkData | null> {
        await this.init();
        return new Promise((resolve, reject) => {
            const transaction = this.db!.transaction(['bookmarks'], 'readonly');
            const store = transaction.objectStore('bookmarks');
            const request = store.get(bookId);

            request.onerror = () => reject(request.error);
            request.onsuccess = () => resolve(request.result || null);
        });
    }

    async removeBookmark(bookId: string): Promise<void> {
        await this.init();
        return new Promise((resolve, reject) => {
            const transaction = this.db!.transaction(['bookmarks'], 'readwrite');
            const store = transaction.objectStore('bookmarks');
            const request = store.delete(bookId);

            request.onerror = () => reject(request.error);
            request.onsuccess = () => resolve();
        });
    }
}

export const bookmarkDB = new BookmarkDB(); 